import {reqSendCode,reqRegister,reqLogin,reqUserInfo,reqlogout} from '@/api'
import { setToken,getToken,clearToken } from '@/utils/token'
const state = {
    code:'',
    token:getToken(),
    userInfo:{}
}
const actions = {
    // 请求验证码
   async getCode({commit},phone){
            let result = await reqSendCode(phone)
            if(result.code == 200){
                commit('GETCODE',result.data)
                return 'ok'
            }else{
                return Promise.reject(new Error('faile'))
            }
    },
    // 注册成功
   async userRegister({commit},{phone,code,password}){
        let result = await reqRegister(phone,code,password);
        console.log(result.code)
        if(result.code == 200){
            return 'ok'
        }else{
            return   Promise.reject(result.message);
        }
    },
    // 用户登录
    async login({commit},{phone,password}){
        let result = await reqLogin(phone,password);
        if(result.code == 200){
            commit('LOGIN',result.data.token)
            setToken(result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo();
        if(result.code == 200){
            commit('GETUSERINFO',result.data)
        }
    },
    // 退出登录
   async loginOut({commit}){
        let result = await reqlogout();
        if(result.code == 200){
            commit('LOGINOUT')
        }
    }
}
const mutations ={
    GETCODE(state,code){
        state.code = code
    },
    LOGIN(state,token){
        state.token = token
    },
    // 获取用户信息
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    // 退出登录  删除token 和userInfo  以及本地存储的Token
    LOGINOUT(state){
        state.token="";
        state.userInfo = {};
        clearToken();
    }
}
const getters = {}
export default{
    state,
    actions,
    mutations,
    getters
}